package charles.testproject.parserlw;

import java.util.Iterator;
import java.util.Vector;

public class ParserLW {

	public static void main(String[] args) {
		String test = "37 46 30N,122 25 10W";
		ParserLW plw = new ParserLW();
		System.out.println(plw.transform(test));

	}

	private String transform(String locationLW) {
		
		LaLoContainer laloCon = new LaLoContainer();
		
		Boolean la = false;
		Boolean lo = false;
		
		String latitude = null;
		String longitude = null;
		
		String strParameter[] = locationLW.split(",");
		if(strParameter.length == 2) {
			latitude = strParameter[0];
			longitude = strParameter[1];
		} else {
			System.out.println("wrong..");
		}
		if(latitude.endsWith("N")) {
			la = true;
		}
		
		if(longitude.endsWith("E")) {
			lo = true;
		}
		
		while (true) {
		      int n = latitude.length();
		                
		      if (Character.isDigit(latitude.charAt(n -1))) break;
		      
		      latitude = latitude.substring(0, n - 1);
		}
		
		while (true) {
		      int n = longitude.length();
		                
		      if (Character.isDigit(longitude.charAt(n-1))) break;
		      
		      longitude = longitude.substring(0, n - 1);
		}
		
		String latitudePara[] = latitude.split(" ");
		
		laloCon.ai = Integer.parseInt(latitudePara[0]);
		laloCon.am = Integer.parseInt(latitudePara[1]);
		laloCon.as = Integer.parseInt(latitudePara[2]);
		
		laloCon.ad = la;
		
		String longitudePara[]= longitude.split(" ");
		
		laloCon.oi = Integer.parseInt(longitudePara[0]);
		laloCon.om = Integer.parseInt(longitudePara[1]);
		laloCon.os = Integer.parseInt(longitudePara[2]);
		
		laloCon.ad = lo;

		String ret = getGEMString(laloCon.ai,laloCon.am,laloCon.as,laloCon.ad,
				laloCon.oi,laloCon.om,laloCon.os,laloCon.od);
		
		return ret;
	}
	
		public String getGEMString(int ai, int am, int as, boolean ad, int oi, int om, int os, boolean od) { 
			final int ACCURACY = 10000000; 
			double la = ai + am / 60.0 + as / 3600.0 * (ad ? 1 : -1); 
			double lo = oi + om / 60.0 + os / 3600.0 * (od ? 1 : -1); 
			long lla = Math.round(la * ACCURACY); 
			long llo = Math.round(lo * ACCURACY);
			String sla = Long.toString(lla / ACCURACY) + "." + Long.toString(Math.abs(lla) % ACCURACY + ACCURACY).substring(1); 
			String slo = Long.toString(llo / ACCURACY) + "." + Long.toString(Math.abs(llo) % ACCURACY + ACCURACY).substring(1); 
			return sla + "," + slo; 
		}
		/**
		 *  a container class that contains the longitude and latitude 
		 *  information.
		 *  i.e.  <37:46:30N 122:25:10W> --- ai:am:as ad oi:om:os od
		 *  if there is N and E ad and od will be true, otherwise be false
		 */
		private class LaLoContainer{
			public int ai = 0;
			public int am = 0;
			public int as = 0;
			
			public boolean ad = false;
			
			public int oi = 0;
			public int om = 0;
			public int os = 0;
			
			public boolean od = false;
			
		}
	
}
